package com.codeying.servlet.admin;

import com.codeying.servlet.AbsServlet;
import com.codeying.entity.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.*;
import com.codeying.utils.*;
import com.codeying.utils.component.*;

/**
 * 保存和新增管理员
 */
@WebServlet("/admin/save")
public class SaveAdminServlet extends AbsServlet {

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setContentType("application/json; charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        int res=0;
        Admin entityTemp=new Admin ();
        //将参数全部转化成Map格式
        Map<String, Object> reqMap = CommonUtils.requestToMap(req);
        String id = (String) reqMap.get("id");
        entityTemp.setId(id);
                                        String username = ""; //用户名
                                            String password = ""; //密码
                                            String name = ""; //姓名
                                            String tele = ""; //电话
                                        username = (String)reqMap.get("username");
            entityTemp.setUsername (username);//String类型参数
                password = (String)reqMap.get("password");
            entityTemp.setPassword (password);//String类型参数
                name = (String)reqMap.get("name");
            entityTemp.setName (name);//String类型参数
                tele = (String)reqMap.get("tele");
            entityTemp.setTele (tele);//String类型参数

        //新增或更新
        if(entityTemp.getId() == 0 || "".equals(entityTemp.getId())){//新增
        id = String.valueOf(CommonUtils.newId());
        entityTemp.setId (id);
        //如果有唯一字段，则在此校验 （字段不为空在前端校验）
                                        if( adminService.getBy("username",entityTemp.getUsername()) != null){
                resp.getWriter().print(ApiResult.fail("用户名 已存在！"));
                return;
                }
                                                            //=========添加之前
            //=========添加之前
            res = adminService.insert(entityTemp);
        }else {
            //=========修改之前
            //=========修改之前
            res = adminService.updateById(entityTemp);
        }

        if(res !=0){
            resp.getWriter().print(ApiResult.success());//标记保存成功
        }else {
            resp.getWriter().print(ApiResult.fail("保存失败"));//保存失败
        }
    }
}

